<template>
  <div class="container">
    <div class="container__header">
      <Header :currentId="8" />
    </div>
    <div class="container__content">
      <div class="container__content__opration">
        <div class="justify-start">
          <date-tab ref="reset" @selectDate="handleSelectDate"></date-tab>
          <el-form ref="form" :model="form" label-width="100px" class="justify-start" style="height: fit-content;">
            <el-form-item label="名字">
              <el-input v-model="form.userName" placeholder="请输入" size="medium"></el-input>
            </el-form-item>
            <el-form-item label="工号">
              <el-input v-model="form.userNo" placeholder="请输入" size="medium"></el-input>
            </el-form-item>
            <el-form-item label="出勤筛选">
              <el-select v-model="form.status" size="medium" placeholder="请选择">
                <el-option label="全部" value=""></el-option>
                <el-option label="正常" :value="1"></el-option>
                <el-option label="迟到" :value="2"></el-option>
                <el-option label="迟到早退" :value="3"></el-option>
                <el-option label="早退" :value="5"></el-option>
                <el-option label="旷工" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="opration-btn">
          <span class="opration-btn__reserve" @click="reserveParams()">重置</span>
          <span class="opration-btn__search" @click="searchList()">开始检索</span>
        </div>
      </div>

      <div class="container__content__table">
        <div class="title justify-between">
          <span>考勤记录</span>
          <span class="download" @click="exportExcel()">导出Excel</span>
        </div>
        <div style="max-height: 734px; width: 100%">
          <el-scrollbar style="max-height: 100%">
            <el-table max-height="734" :data="tableData" style="width: 100%; margin-top: 12px; background-color: #303136" :border="false">
              <el-table-column prop="index" label="序号"> </el-table-column>
              <el-table-column prop="nickname" label="名字"> </el-table-column>
<!--              <el-table-column prop="postNo" label="工号"> </el-table-column>-->
              <el-table-column prop="phone" label="联系方式"> </el-table-column>
              <el-table-column prop="firstTime" label="上班时间">
              </el-table-column>
              <el-table-column prop="endTime" label="下班时间">
              </el-table-column>
              <el-table-column prop="isOutEarlier" label="是否早退">
              </el-table-column>
              <el-table-column prop="isLate" label="是否迟到">
              </el-table-column>
              <el-table-column prop="isLost" label="是否旷工">
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </div>

        <div class="table-pagination">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNo" :page-sizes="pageSizeArr" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";
import DateTab from "@/components/DateTab.vue";
import { getWorkList, exportSnapExcel } from "@/api/home";
import { timestampToDate } from "@/utils/dateUtils";
export default {
  name: "RuleView",
  components: {
    Header,
    DateTab
  },

  data() {
    return {
      pageSizeArr: [10, 20, 30, 40, 50, 60],
      pageSize: 20,
      pageNo: 1,
      totalCount: 0,
      startTime: null,
      endTime: null,
      dateType: 3,

      value: "",
      form: {
        userName: "",
        userNo: "",
        status: ""
      },
      tableData: []
    };
  },
  mounted() {
    this.getWorkLists();
  },
  methods: {
    //日期选择
    handleSelectDate(e) {
      this.startTime = new Date(`${e.date[0]} 00:00:00`).getTime() / 1000;
      this.endTime = new Date(`${e.date[1]} 23:59:59`).getTime() / 1000;

      this.dateType = e.dateType;
    },
    //获取参数
    getParams() {
      return {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        startTime: this.startTime,
        endTime: this.endTime,
        dayType: this.dateType,
        status: this.form.status,
        userName: this.form.userName,
        userNo: this.form.userNo
      };
    },

    //开始检索
    searchList() {
      this.pageNo = 1;
      this.tableData = [];
      this.getWorkLists();
    },

    //重置条件
    reserveParams() {
      this.form = {
        userName: "",
        userNo: "",
        status: ""
      };
      this.searchList();
      this.$refs.reset.reset()
    },
    //规则列表
    async getWorkLists() {
      let params = this.getParams();
      let res = await getWorkList(params);
      if (res.code == 200) {
        console.log(res);
        this.tableData = res.data.lists;
        this.totalCount = res.data.count;
      }

      let index = 1
      this.tableData.forEach((item)=>{
        Object.assign(item, {index:index++});
        item.firstTime = this.TimestampToDate(item.firstTime)
        item.endTime = this.TimestampToDate(item.endTime)
      })
    },

    //导出规则列表
    async exportExcel() {
      let params = this.getParams();
      let res = await exportSnapExcel(params);
      if (res) {
        const startTimeDate = timestampToDate(this.startTime);
        const endTimeDate = timestampToDate(this.endTime);
        let data = "考勤" + startTimeDate + "至" + endTimeDate + "data.xlsx"
        const blob = new Blob([res], {
          type:
              "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8"
        });
        try {
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, data);
          } else {
            let downloadElement = document.createElement('a');
            let href = window.URL.createObjectURL(blob); // 创建下载的链接
            downloadElement.href = href;
            downloadElement.download = data; // 下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); // 点击下载
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
            this.$message.success("考勤导出成功");

          }
        }catch (e) {
          this.$message.error("考勤导出失败");
        }


        //   const TEXT = await new Response(blob).text(); // 获取文本内容
        //   const obj = eval(`( ${TEXT} )`); // blob转obj
        //
        //   if (obj.code !== 200) {
        //     this.$message.error(obj.msg);
        //   } else {
        //     const url = URL.createObjectURL(blob);
        //     const link = document.createElement("a");
        //     link.href = url;
        //     const startTimeDate = timestampToDate(this.startTime);
        //
        //     const endTimeDate = timestampToDate(this.endTime);
        //
        //     link.download =
        //       "考勤" + startTimeDate + "至" + endTimeDate + "data.xlsx";
        //
        //     document.body.appendChild(link);
        //     link.click();
        //     document.body.removeChild(link);
        //
        //     URL.revokeObjectURL(url);
        //     this.$message.success("考勤导出成功");
        //   }
        // } else {
        //   this.$message.error("考勤导出失败");
        // }
      }
    },

    handleCurrentChange(e) {
      this.pageNo = e;
      this.tableData = [];
      this.getWorkLists();
    },

    handleSizeChange(e) {
      this.pageSize = e;
      this.pageNo = 1;
      this.tableData = [];
      this.getWorkLists();
    },
    TimestampToDate(Timestamp) {
      Timestamp = parseInt(Timestamp)
      if (isNaN(Timestamp)) return '未知时间'
  let date1 = new Date(Timestamp* 1000);
  return date1.toLocaleDateString().replace(/\//g, "-") + " " + date1.toTimeString().substr(0, 8);
}

  }
};
</script>

<style lang="scss" scoped>
.container {
  background: #303136;
  &__content {
    &__opration {
      margin-top: 16px;
      padding: 0 24px;
      width: 100%;
      height: 84px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #3b3e42;

      .opration-btn {
        span {
          display: inline-block;
          width: 88px;
          height: 36px;
          line-height: 36px;
          border-radius: 4px;
          cursor: pointer;
        }

        &__reserve {
          border: 1px solid #5cfbff;
          color: #5cfbff;
          margin-right: 24px;
        }

        &__search {
          background-color: #5cfbff;
          color: #17181a;
        }
      }
    }

    &__table {
      width: 100%;
      padding: 24px;
      color: #fff;
      .download {
        cursor: pointer;
        display: block;
        width: 98px;
        height: 36px;
        background-color: #404249;
        text-align: center;
        line-height: 36px;
        border-radius: 4px;
        margin-left: 91.3%;
      }

      .table-pagination {
        width: 100%;
        text-align: right;
        margin: 30px 0;
      }
    }
  }
}
::v-deep .el-form-item {
  margin-bottom: 0;
}
</style>

